package main

import (
	"log"
	"io/ioutil"
	"os"
	"os/exec"
)

func editNewFile(cfg *Config) (string, error) {
	// create temp file
	f, err := ioutil.TempFile(os.TempDir(), "recp")
	if err != nil {
		return "", nil
	}
	filename := f.Name()
	f.Close()

	// write temp file
	ioutil.WriteFile(filename, []byte(cfg.basicFile), 0666)

	// open editor
	err = editFile(cfg, filename, cfg.basicFile)
	if err != nil {
		return filename, err
	}

	return filename, nil
}


func editFile(cfg *Config, filename string, original_content string) error {
	cmd := exec.Command(cfg.editor, filename)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		return err
	}
	if !fileWasEdited(filename, original_content) {
		return &FileNotChangedError{}
	}
	return nil
}


func fileWasEdited(filename string, original string) bool {
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatal(err)
	}
	return (string(b) != original)
}


type FileNotChangedError struct {}
func (e *FileNotChangedError) Error() string { return "File not changed." }
